package com.example.managemyself.viewmodel;

import android.app.Application;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Transformations;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.example.managemyself.data.model.DiaryEntry;
import com.example.managemyself.data.model.Task;
import com.example.managemyself.data.model.User;
import com.example.managemyself.data.repository.DiaryRepository;
import com.example.managemyself.data.repository.TaskRepository;
import com.example.managemyself.util.UserManager;

/**
 * 日记ViewModel，处理日记相关的UI逻辑
 * 支持用户数据隔离
 */
public class DiaryViewModel extends AndroidViewModel {
    
    private final DiaryRepository diaryRepository;
    private final TaskRepository taskRepository;
    private final UserManager userManager;
    
    // 根据当前用户过滤的日记数据
    private final LiveData<List<DiaryEntry>> allDiaryEntries;
    private final MutableLiveData<DiaryEntry> selectedDiaryEntry = new MutableLiveData<>();
    
    // 用于驱动数据变化的日期信号
    private final MutableLiveData<Date> selectedDate = new MutableLiveData<>();
    
    // 当 selectedDate 变化时，这个 LiveData 会自动切换去观察新日期对应的日记条目
    public final LiveData<DiaryEntry> diaryForSelectedDate;
    
    public DiaryViewModel(Application application) {
        super(application);
        diaryRepository = new DiaryRepository(application);
        taskRepository = new TaskRepository(application);
        userManager = UserManager.getInstance();
        
        // 获取当前用户的所有日记
        allDiaryEntries = getCurrentUserDiaryEntries();
        
        diaryForSelectedDate = Transformations.switchMap(selectedDate, date -> 
            getCurrentUserDiaryEntryByDate(date)
        );
    }
    
    /**
     * 获取当前用户的所有日记条目
     */
    private LiveData<List<DiaryEntry>> getCurrentUserDiaryEntries() {
        User currentUser = userManager.getCurrentUser();
        if (currentUser != null) {
            return diaryRepository.getDiaryEntriesByUserId(currentUser.getId());
        } else {
            // 如果没有当前用户，返回空列表
            MutableLiveData<List<DiaryEntry>> emptyList = new MutableLiveData<>();
            emptyList.setValue(java.util.Collections.emptyList());
            return emptyList;
        }
    }
    
    /**
     * 获取当前用户指定日期的日记条目
     */
    private LiveData<DiaryEntry> getCurrentUserDiaryEntryByDate(Date date) {
        User currentUser = userManager.getCurrentUser();
        if (currentUser != null) {
            return diaryRepository.getDiaryEntryByDateAndUserId(date, currentUser.getId());
        } else {
            MutableLiveData<DiaryEntry> emptyDiary = new MutableLiveData<>();
            emptyDiary.setValue(null);
            return emptyDiary;
        }
    }
    
    // 获取所有日记
    public LiveData<List<DiaryEntry>> getAllDiaryEntries() {
        return allDiaryEntries;
    }
    
    // 根据ID获取日记（带用户验证）
    public LiveData<DiaryEntry> getDiaryEntryById(int id) {
        User currentUser = userManager.getCurrentUser();
        if (currentUser != null) {
            return diaryRepository.getDiaryEntryByIdAndUserId(id, currentUser.getId());
        } else {
            MutableLiveData<DiaryEntry> emptyDiary = new MutableLiveData<>();
            emptyDiary.setValue(null);
            return emptyDiary;
        }
    }
    
    // 根据日期范围获取日记（当前用户）
    public LiveData<List<DiaryEntry>> getDiaryEntriesByDateRange(Date startDate, Date endDate) {
        User currentUser = userManager.getCurrentUser();
        if (currentUser != null) {
            return diaryRepository.getDiaryEntriesByDateRangeAndUserId(startDate, endDate, currentUser.getId());
        } else {
            MutableLiveData<List<DiaryEntry>> emptyList = new MutableLiveData<>();
            emptyList.setValue(java.util.Collections.emptyList());
            return emptyList;
        }
    }
    
    // 根据日期获取日记（当前用户）
    public LiveData<DiaryEntry> getDiaryEntryByDate(Date date) {
        return getCurrentUserDiaryEntryByDate(date);
    }
    
    // 根据日期获取日记（同步方法，当前用户）
    public DiaryEntry getDiaryByDateSync(Date date) {
        User currentUser = userManager.getCurrentUser();
        if (currentUser != null) {
            return diaryRepository.getDiaryByDateAndUserIdSync(date, currentUser.getId());
        }
        return null;
    }
    
    // 搜索日记（当前用户）
    public LiveData<List<DiaryEntry>> searchDiaryEntries(String keyword) {
        User currentUser = userManager.getCurrentUser();
        if (currentUser != null) {
            return diaryRepository.searchDiaryEntriesByUserId(keyword, currentUser.getId());
        } else {
            MutableLiveData<List<DiaryEntry>> emptyList = new MutableLiveData<>();
            emptyList.setValue(java.util.Collections.emptyList());
            return emptyList;
        }
    }
    
    // 插入日记（自动设置用户ID）
    public void insertDiaryEntry(DiaryEntry diaryEntry) {
        User currentUser = userManager.getCurrentUser();
        if (currentUser != null) {
            diaryEntry.setUserId(currentUser.getId());
            diaryRepository.insertDiaryEntry(diaryEntry);
        }
    }
    
    // 插入日记（简化方法名）
    public void insertDiary(DiaryEntry diaryEntry) {
        insertDiaryEntry(diaryEntry);
    }
    
    // 更新日记（验证用户权限）
    public void updateDiaryEntry(DiaryEntry diaryEntry) {
        User currentUser = userManager.getCurrentUser();
        if (currentUser != null && diaryEntry.getUserId() == currentUser.getId()) {
            diaryRepository.updateDiaryEntry(diaryEntry);
        }
    }
    
    // 更新日记（简化方法名）
    public void updateDiary(DiaryEntry diaryEntry) {
        updateDiaryEntry(diaryEntry);
    }
    
    // 删除日记（验证用户权限）
    public void deleteDiaryEntry(DiaryEntry diaryEntry) {
        User currentUser = userManager.getCurrentUser();
        if (currentUser != null && diaryEntry.getUserId() == currentUser.getId()) {
            diaryRepository.deleteDiaryEntry(diaryEntry);
        }
    }
    
    // 根据ID删除日记（验证用户权限）
    public void deleteDiaryEntryById(int id) {
        User currentUser = userManager.getCurrentUser();
        if (currentUser != null) {
            // 先获取日记条目验证权限
            DiaryEntry diary = diaryRepository.getDiaryByIdSync(id);
            if (diary != null && diary.getUserId() == currentUser.getId()) {
                diaryRepository.deleteDiaryEntryById(id);
            }
        }
    }
    
    // 设置选中的日记
    public void selectDiaryEntry(DiaryEntry diaryEntry) {
        selectedDiaryEntry.setValue(diaryEntry);
    }
    
    // 获取选中的日记
    public LiveData<DiaryEntry> getSelectedDiaryEntry() {
        return selectedDiaryEntry;
    }
    
    // 创建新日记（自动设置用户ID）
    public DiaryEntry createNewDiaryEntry(String title, String content) {
        User currentUser = userManager.getCurrentUser();
        DiaryEntry diaryEntry = new DiaryEntry(title, content, new Date());
        if (currentUser != null) {
            diaryEntry.setUserId(currentUser.getId());
        }
        return diaryEntry;
    }
    
    /**
     * 保存日记，并将当天已完成的任务归档，然后从任务列表删除
     * @param diaryEntry 要保存的日记条目
     * @param completedTasks 当天已完成的任务列表
     */
    public void saveDiaryAndArchiveTasks(DiaryEntry diaryEntry, List<Task> completedTasks) {
        User currentUser = userManager.getCurrentUser();
        if (currentUser == null) {
            return;
        }
        
        // 1. 将已完成任务的标题追加到日记内容中
        String archivedTasksContent = completedTasks.stream()
                .map(task -> "- " + task.getTitle())
                .collect(Collectors.joining("\n"));
        
        String originalContent = diaryEntry.getContent() != null ? diaryEntry.getContent() : "";
        diaryEntry.setContent(originalContent + "\n\n--- 自动记录的已完成任务 ---\n" + archivedTasksContent);

        // 2. 设置用户ID并保存日记条目
        diaryEntry.setUserId(currentUser.getId());
        diaryRepository.insertDiaryEntry(diaryEntry);

        // 3. 提取已完成任务的ID列表（只处理当前用户的任务）
        List<Integer> taskIdsToDelete = completedTasks.stream()
                .map(Task::getId)
                .collect(Collectors.toList());

        // 4. 从任务数据库中删除这些任务
        if (!taskIdsToDelete.isEmpty()) {
            taskRepository.deleteTasksByIds(taskIdsToDelete);
        }
    }
    
    /**
     * 设置要观察的日期，这将触发 diaryForSelectedDate 的更新
     * @param date 新选择的日期
     */
    public void selectDate(Date date) {
        selectedDate.setValue(date);
    }
    
    /**
     * 刷新当前用户的日记数据
     * 当用户切换时调用
     */
    public void refreshUserData() {
        // 重新初始化数据源
        // 这会触发LiveData的重新订阅
        selectedDate.setValue(selectedDate.getValue());
    }
}
